package Solutions;



/***
 * 给定一个字符串<code>string</code>和一个<code>int</code>整型的数据<code>num</code>，将该字符串的前
 * <code>num</code>个字符构成的字串，放置剩下的字串的后面，构成新的<code>String</code>对象返回
 */
public class ReverseString {

    /***
     * 返回对应的字符串
     * @param string 输入字符串
     * @param num 反转的字符数量
     * @return res
     */
    public String reverseString(String string, int num) {
        if ((string == null || num == 0) || string.length() == num) return string;
        if (string.length() < num || num < 0)
            throw new RuntimeException("The input params are illegal!");
        return reverse(reverse(string.substring(0, num)) + reverse(string.substring(num)));
    }

    /***
     * 反转字符串
     * @param str 给定字符串
     * @return 反转字符串
     */
    public String reverse(String str) {
        char[] chars = str.toCharArray();
        char[] res = new char[str.length()];
        for (int i = 0, j = chars.length - 1; i < chars.length && j >= 0; i++, j--) {
            res[i] = chars[j];
        }
        return String.valueOf(res);
    }





    public String wordReverse(String str) {
        String[] words = str.split(" ");
        return wordReverse(words);
    }

    public String wordReverse(String[] words) {
        String[] res = new String[words.length];
        StringBuilder sb = new StringBuilder();
        for (int i = 0, j = words.length - 1; i < words.length && j >= 0; i++, j--) {
            res[i] = words[j];
        }
        for (int i = 0; i < res.length; i++) {
            sb.append(res[i]);
            if (i != res.length - 1) sb.append(" ");
        }
        return sb.toString();
    }


    public static void main(String[] args) {
        System.out.println(new ReverseString().reverseString("abcdefgh", 5));
        System.out.println(new ReverseString().wordReverse("I am a cool boy."));
    }
}
